package com.example.weather_app.diary;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.weather_app.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DiaryDetailActivity extends AppCompatActivity {
    private TextView tvTitle, tvDate, tvContent, tvReminder;
    private DiaryDao diaryDao;
    private Diary diary;
    private String diaryId;
    private SimpleDateFormat dateFormat, timeFormat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_detail);

        // 设置Toolbar
        androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("日记详情");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // 初始化组件
        tvTitle = findViewById(R.id.tvTitle);
        tvDate = findViewById(R.id.tvDate);
        tvContent = findViewById(R.id.tvContent);
        tvReminder = findViewById(R.id.tvReminder);
        diaryDao = new DiaryDao(this);
        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        timeFormat = new SimpleDateFormat("HH:mm", Locale.CHINA);

        // 获取日记ID
        if (getIntent() != null && getIntent().hasExtra("diaryId")) {
            diaryId = getIntent().getStringExtra("diaryId");
            loadDiary(diaryId);
        } else {
            Toast.makeText(this, "日记ID不存在", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    // 加载日记数据
    private void loadDiary(String id) {
        diary = diaryDao.getDiaryById(id);
        if (diary != null) {
            tvTitle.setText(diary.getTitle());
            tvDate.setText("日期: " + diary.getDate());
            tvContent.setText(diary.getContent());

            // 处理提醒时间
            if (diary.getReminderTime() != null && !diary.getReminderTime().isEmpty()) {
                try {
                    SimpleDateFormat fullDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    java.util.Date reminderDate = fullDateFormat.parse(diary.getReminderTime());
                    String time = timeFormat.format(reminderDate);
                    tvReminder.setText("提醒时间: " + dateFormat.format(reminderDate) + " " + time);
                    tvReminder.setVisibility(View.VISIBLE);
                } catch (ParseException e) {
                    tvReminder.setVisibility(View.GONE);
                    e.printStackTrace();
                }
            } else {
                tvReminder.setVisibility(View.GONE);
            }
        } else {
            Toast.makeText(this, "日记不存在", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    // 创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.diary_detail_menu, menu);
        return true;
    }

    // 菜单点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_edit) {
            // 编辑日记
            editDiary();
            return true;
        } else if (id == R.id.action_delete) {
            // 删除日记
            showDeleteConfirmation();
            return true;
        } else if (id == android.R.id.home) {
            // 返回
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // 编辑日记
    private void editDiary() {
        Intent intent = new Intent(this, EditDiaryActivity.class);
        intent.putExtra("diaryId", diaryId);
        startActivityForResult(intent, 1);
    }

    // 显示删除确认对话框
    private void showDeleteConfirmation() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除日记");
        builder.setMessage("确定要删除这篇日记吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteDiary();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    // 删除日记
    private void deleteDiary() {
        if (diary != null) {
            // 取消提醒
            if (diary.getReminderTime() != null && !diary.getReminderTime().isEmpty()) {
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Intent intent = new Intent(this, ReminderReceiver.class);
                intent.setAction("com.example.weather_app.ACTION_DIARY_REMINDER");
                intent.putExtra("diaryId", diaryId);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        this,
                        diaryId.hashCode(),
                        intent,
                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
                );

                alarmManager.cancel(pendingIntent);
            }

            // 删除日记
            diaryDao.deleteDiary(diaryId);
            Toast.makeText(this, "日记已删除", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);
            finish();
        }
    }

    // 处理编辑返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 刷新日记数据
            loadDiary(diaryId);
        }
    }
}